package tinyinventor;

import codeblocks.Block;
import codeblocks.BlockConnector;
import codeblocks.LinkRule;

/**
 * Simple socket rule which enables links to connect if they are the same kind
 * or if one is subkind of the other. Subkinds are defined with their superkind
 * as a prefix. 
 * 
 * @author Morten Tranberg Hansen
 *
 */

public class SocketRule implements LinkRule {

	public boolean canLink(Block block1, Block block2, BlockConnector socket1, BlockConnector socket2) {
		
		// Make sure that none of the sockets are connected,
		// and that exactly one of the sockets is a plug.
		if (socket1.hasBlock() || socket2.hasBlock() ||
			!((block1.hasPlug() && block1.getPlug() == socket1) ^
			  (block2.hasPlug() && block2.getPlug() == socket2))) {
			return false;
		}
		
		// If they don't have same kind, then they cannot connect
		// Sub-types is defined with the prefix of the super type.
		if (socket1.getKind().startsWith(socket2.getKind()) || socket2.getKind().startsWith(socket1.getKind())) {
			return true;
		}
		
		return false;
	}

	public boolean isMandatory() {
		return false;
	}
	
}
